package com.thiswhyme.hystrix.server1.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.thiswhyme.common.response.ResponseCode;
import com.thiswhyme.common.response.ResponseVo;
import com.thiswhyme.hystrix.server1.controller.dto.UserDto;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * Created by thiswhyme on 2020/9/3.
 */
@RestController
@RequestMapping("/user1/")
public class UserController {

    // http://localhost:8081/user1/user-info
    @HystrixCommand(commandKey = "user-info", fallbackMethod = "queryUserInfoFallback")
    @GetMapping("user-info")
    public ResponseVo<UserDto> queryUserInfo() throws InterruptedException {
        Thread.sleep(2000);
        return ResponseVo.success(new UserDto().setUserId(666).setName("sentinel-test"));
    }

    // http://localhost:8081/user1/user-list
    @HystrixCommand(commandKey = "user-list", fallbackMethod = "listUserInfoFallback")
    @GetMapping("user-list")
    public ResponseVo<List<UserDto>> listUserInfo() throws InterruptedException {
        Thread.sleep(2000);
        return ResponseVo.success(Arrays.asList(new UserDto().setUserId(666).setName("sentinel-test"),
                new UserDto().setUserId(888).setName("sentinel-test2")));
    }

    // http://localhost:8081/user1/user-name?userId=12
    @GetMapping("user-name")
    public ResponseVo<String> queryUserName(@RequestParam Integer userId) throws Exception{
        Thread.sleep(2000);
        return ResponseVo.success(userId + "sentinel-test");
    }

    public ResponseVo<UserDto> queryUserInfoFallback(){
        return ResponseVo.failure(ResponseCode.SYSTEM_EXCEPTION.getCode(), "hystrix queryUserInfoFallback");
    }

    public ResponseVo<List<UserDto>> listUserInfoFallback(){
        return ResponseVo.failure(ResponseCode.SYSTEM_EXCEPTION.getCode(), "hystrix listUserInfoFallback");
    }
}
